//: Playground - noun: a place where people can play

import UIKit
import Foundation


var str = "Hello, playground"

var backView = UIView()
backView.frame = CGRect(x:0, y:0, width:100, height:100)
backView.backgroundColor = UIColor.red

//使用预定义颜色之一
let redColor = UIColor.red
let blueColor:UIColor = .blue

//如果编译器已经知道变量是一个实例，UIColor可以一起跳过类型
let view = UIView()
view.backgroundColor = .yellow

//使用灰度值和alpha
let grayscaleColor = UIColor(white: 0.5, alpha: 1.0)

//使用包调，饱和度，亮度和alpha
let hsbColor = UIColor(hue: 30.0/255,
                       saturation: 70.0/255,
                       brightness: 200.0/255,
                       alpha: 1.0)

//使用RGBA值
let rgbColor = UIColor(red: 30.0/255,
                       green: 70.0/255,
                       blue: 200.0/255,
                       alpha: 1.0)

//使用图案图片
let image = UIImage(named: "myImage.JPG")
let patternColor = UIColor(patternImage: image!)

//从十六进制数或字符串创建UIColor
/** Int值 */
extension UIColor {
    convenience init(hex:Int, alpha:CGFloat = 1.0){
        let r = CGFloat((hex >> 16) & 0xff) / 255
        let g = CGFloat((hex >> 08) & 0xff) / 255
        let b = CGFloat((hex >> 00) & 0xff) / 255
        self.init(red: r, green:g, blue:b, alpha:alpha)
    }
}

let color = UIColor(hex: 0xff00cc, alpha: 1.0)
//由于已经设置了alpha的默认值为1.0
let color1 = UIColor(hex: 0xff00cc)

/**字符串*/
extension UIColor {
    convenience init(hexCode:String){
        let hex = hexCode.trimmingCharacters(in: CharacterSet().inverted)
        var int = UInt32()
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b:UInt32
        
        switch hex.count {
        case 3:
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
            
        case 6:
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
            
        case 8:
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
            
        default:
            (a, r, g, b) = (1, 1, 1, 0)
        }
        
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue:CGFloat(b) / 255, alpha:CGFloat(a) / 255)
    }
  
}

let color2 = UIColor(hexCode: "#80ffffff")

let color3 = UIColor(hexCode: "#FFFFFF")

let imgcolor = UIColor(named: "myImage.JPG")












